package com.liufei.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author LiuFei
 * @create 2017-12-25 11:01
 */
public class DatabaseUtils {

    public static String driverClass = null;
    public static String url = null;
    public static String username = null;
    public static String password = null;

    static {
        Properties properties = new Properties();
        InputStream resourceAsStream = DatabaseUtils.class.getResourceAsStream("/jdbc.properties");
        try {
            properties.load(resourceAsStream);
            driverClass = properties.getProperty("jdbc.driverClass");
            url = properties.getProperty("jdbc.url");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            Class.forName(driverClass);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void closeConnection(Connection connection) {

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
